// src/store/modules/taskEvaluation.js

import { fetchCompletedTasks, submitTaskEvaluation } from '@/api/taskEvaluation';

const state = {
  completedTasks: []
};

const mutations = {
  SET_COMPLETED_TASKS(state, tasks) {
    state.completedTasks = tasks;
  },
  UPDATE_TASK_EVALUATION(state, { taskId, rating, comment, evaluator }) {
    const task = state.completedTasks.find(task => task.id === taskId);
    if (task) {
      task.rating = rating;
      task.comment = comment;
      task.evaluator = evaluator;
    }
  }
};

const actions = {
  async fetchCompletedTasks({ commit }) {
    try {
      const response = await fetchCompletedTasks();
      commit('SET_COMPLETED_TASKS', response.data); // 确保API返回的数据格式正确
    } catch (error) {
      console.error('Failed to fetch completed tasks:', error.message);
    }
  },
  async submitTaskEvaluation({ commit }, { taskId, rating, comment, evaluator }) {
    try {
      await submitTaskEvaluation({ taskId, rating, comment, evaluator });
      commit('UPDATE_TASK_EVALUATION', { taskId, rating, comment, evaluator });
      return true;
    } catch (error) {
      console.error('Failed to submit task evaluation:', error.message);
      return false;
    }
  }
};

const getters = {
  getCompletedTasks: state => state.completedTasks
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
};